/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 * 这是一个公共的入口，保持Android和IOS的统一入口
 */

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  TextInput,
  Button,
  Platform,  //使用平台方法来判断是Android还是IOS
  Dimensions,
  ListView,
  Alert,
  TouchableHighlight,//用于封装响应组件
  StatusBar, //用于状态栏设置
  Image,
  RefreshControl,//拖拽刷新组件
} from 'react-native';
import Swiper from 'react-native-swiper';
import { Thumbnail } from 'native-base';//远程图片获取
//创建ListView数据源
const ds = new ListView.DataSource({
  rowHasChanged: (r1,r2) => r1 !== r2
});
//加入轮播的指示器
const circleSize = 8;
const circleMargin = 5;
//获取网络数据
const SERVER_URL='http://192.168.10.113:3000/';
const PRODUCT_API='products/';
export default class app extends Component {
  constructor(props){
    super(props);
    this.state={
      isRefreshing: false,//是否正在刷新的flag
      searchText: '',
      advertisements:[
        {
          image: require('./images/1.png')
        },{
          image: require('./images/2.png')
        },{
          image: require('./images/3.png')
        },{
          image: require('./images/4.png')
        },{
          image: require('./images/5.png')
        },{
          image: require('./images/6.png')
        },{
          image: require('./images/7.png')
        }
      ],
      currentPage: 0,
      //清空本地数据
      dataSource: ds.cloneWithRows([])
    };
  }
  render() {
    //添加指示器
    const advertisementCount = this.state.advertisements.length;
    //指示器的宽度计算
    const indicatorWidth = circleSize * advertisementCount + circleMargin* advertisementCount * 2;
    const left = (Dimensions.get('window').width - indicatorWidth)/2;
    return (
      <View style={styles.container}>
        <StatusBar backgroundColor={'blue'}
            barStyle={'default'}></StatusBar>
        <View style={styles.searchbar}>
          <TextInput style={styles.input} placeholder ='搜索商品'
            onChangeText={(text) => {
              this.setState({searchText: text});
              console.log('输入的内容是：'+this.state.searchText);
            }}></TextInput>
          <Button style={styles.button} 
            title='搜索'
            onPress={() => Alert.alert('搜索内容: '+this.state.searchText,null,null)}></Button>
        </View>
        <View style={styles.advertisement}>
          <Swiper loop={true} heigth={190} autoplay={true}>
              {this.state.advertisements.map((advertisement,index) => {
                return (
                  <TouchableHighlight key={index} onPress={() => Alert.alert('你单击了轮播图',null,null)}>
                  <Image style={styles.advertisementContent}
                      source={advertisement.image}>
                  </Image>
                  </TouchableHighlight>
                );
              })}
          </Swiper>
          {/* <View style={[
            styles.indicator,{
              left: left
            }
          ]}>
          {this.state.advertisements.map((advertisement,index) => {
            return (<View key={index}
                style={(index === this.state.currentPage)
                ? styles.circleSelected
                : styles.circle}/>);
          })}
          </View> */}
        </View>
        <View style={styles.products}>
          <ListView dataSource={this.state.dataSource} 
              renderRow={this._renderRow}
              renderSeparator={this._renderSeparator}
              refreshControl={this._renderRefreshControl()}
              enableEmptySections={true}/>
        </View>
      </View>
    );
  }
  componentDidMount(){
    this._fetchProducts();
  }
  //让轮播图动起来
   /*componentDidMount(){
    this._startTimer();
  }
  
  componentWillUnmount(){
    clearInterval(this.interval);
  }
 _startTimer(){
    this.interval = setInterval(() => {
      //创建定时器
      nextPage = this.state.currentPage + 1;
      //翻到最后一页直接回到第一页
      if(nextPage >= 7){
        nextPage = 0;
      }
      //更新当前页的值
      this.setState({currentPage: nextPage});
      //计算轮播控件的横向偏移量
      const offSetX = nextPage * Dimensions.get('window').width;
      this.refs.scrollView.scrollResponderScrollTo({x: offSetX,y: 0, animated: true});
    },2000);//设置定时器间隔为2s
  }*/
  _renderRow = (rowData,sectionID,rowID) => {
    return (
      <TouchableHighlight onPress={() => Alert.alert('你单击了商品列表',null,null)}>
      <View style={styles.row}>
        <Thumbnail square size={40} source={{
          uri: SERVER_URL + rowData.image
        }}>
        </Thumbnail>
        <View style={styles.productText}>
        <Text style={styles.productTitle}>{rowData.title}
        </Text>
        <Text style={styles.productSubTitle}>{rowData.subTitle}
        </Text>
        </View>
      </View>
      </TouchableHighlight>
    );
  }
  //渲染分割线
  _renderSeparator(sectionID,rowID,adjacentRowHighlighted){
    return(
      <View key={`${sectionID}-${rowID}`} style={styles.divider}>
      </View>
    );
  }
  //拖拽刷新列表控制
  _renderRefreshControl(){
    return (
      <RefreshControl
        refreshing={this.state.isRefreshing}
        onRefresh={this._onRefresh}
        tintColor={'#FF0000'}
        title={'正在刷新数据，请稍后...'}
        titleColor={'#0000FF'}>
      </RefreshControl>
    );
  }
  //刷新获取数据
  _onRefresh = () =>{
    this.setState({isRefreshing: true});
    setTimeout(() => {
      const products = Array.from(new Array(10)).map((value,index) => ({
        image: require('./images/product_logo.jpg'),
        title: '新商品'+index,
        subTitle: '新的商品描述'+ index
      }));
      this.setState({isRefreshing: false,dataSource: ds.cloneWithRows(products)});
    },2000);
  }
  //获取数据
  _fetchProducts = () =>{
    const req = new Request(SERVER_URL + PRODUCT_API, {
      method: 'GET',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
    });
    console.log('request: ',SERVER_URL + PRODUCT_API);
    fetch(req).then((res) => {
      return res.json();
    }).then((result,done) => {
      if(!done){
        console.log('result:'+ JSON.stringify(result));
        this.setState({dataSource: ds.cloneWithRows(result)});
      }
    }).catch(function (error) {//加上catch 
      console.log(error);
    });
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  searchbar: {
    //判断所用平台不同，marginTop也是不同的
    marginTop: Platform.OS === 'ios'
      ? 20
      : 0,
    height: 40,
    flexDirection: 'row',
  },
  input:{
    flex: 1,
    borderColor: 'gray',
    borderWidth: 2,
    borderRadius: 10
  },
  button: {
    flex: 1
  },
  advertisement: {
    height: 180,
  },
  products:{
    flex: 1,
  },
  row: {
    height: 60,
    flexDirection: 'row',
    backgroundColor: 'white'
  },
  productImage: {
    marginLeft: 10,
    marginRight: 10,
    width: 40,
    height: 40
  },
  productText:{
    flex: 1,
    marginTop: 10,
    marginBottom: 10
  },
  productTitle:{
    flex: 3,
    fontSize: 16,
  },
  productSubTitle: {
    flex: 2,
    fontSize: 14,
    color: 'gray'
  },
  divider: {
    height: 1,
    width: Dimensions.get('window').width - 5,
    marginLeft: 5,
    backgroundColor: 'lightgray'
  },
  advertisementContent: {
    width: Dimensions.get('window').width,
    height: 180
  }
  // indicator: {
  //   position: 'absolute',
  //   top: 160,
  //   flexDirection: 'row',
  // },
  // circle: {
  //   width: circleSize,
  //   height: circleSize,  
  //   borderRadius: circleSize/2,
  //   backgroundColor: 'gray',
  //   marginHorizontal: circleMargin,
  // },
  // circleSelected: {
  //   width: circleSize,
  //   height: circleSize,
  //   borderRadius: circleSize/2,
  //   backgroundColor: 'white',
  //   marginHorizontal: circleMargin,
  // }
});
